/**     
 * @{#} SocketConnector.java Create on 2011-7-22 上午09:20:29     
 *     
 * Copyright (c) 2011 by xiaofeng.zhouxf     
 */
package com.sefer.memcached.connect;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SocketChannel;

import com.sefer.memcached.constants.ErrorCode;
import com.sefer.memcached.exception.ClientException;
import com.sefer.memcached.lifecycle.LifeCycle;

/**
 * @author <a href="mailto:xiaofeng.zhouxf83@gmail.com">xiaofeng.zhouxf</a>
 * @version 1.0
 */
public class DefaultConnectorImpl implements Connector {
	private String lifeCycleStats;
	private Server server;
	private SocketWrap socket;

	private int DEFAULT_TIME_OUT = 30;

	@Override
	public boolean start() throws ClientException {
		if (LifeCycle.STATING == getState()) {
			socket = connect();
			return true;
		}
		return false;
	}

	@Override
	public boolean stop() {
		return false;
	}

	@Override
	public String getState() {
		return lifeCycleStats;
	}

	@Override
	public void setState(String state) {
		this.lifeCycleStats = state;
	}

	@Override
	public void setServer(Server server) {
		this.server = server;
	}

	@Override
	public Server getServer() {
		return server;
	}

	@Override
	public SocketWrap getSocketWrap() {
		return this.socket;
	}

	private SocketWrap connect() {
		SocketChannel sock;
		Socket originSocket;
		try {
			sock = SocketChannel.open();

			sock.socket().connect(
					new InetSocketAddress(server.getIp(), server.getPort()),
					DEFAULT_TIME_OUT);
			originSocket = sock.socket();
		} catch (IOException e) {
			throw new ClientException(ErrorCode.E_500, e, e.getMessage());
		}

		return new SocketWrap(originSocket, this.server);
	}

}
